package org.java.net.socket;

import java.awt.*;
import java.net.*;
import java.io.*;
import java.awt.event.*;
public class Client4 extends Frame implements ActionListener{
  private TextArea msgView=new TextArea();
  private Button kawi, bawi, bo;
  private DataInputStream reader;
  private DataOutputStream writer;
  public static int KAWI=0;
  public static int BAWI=1;
  public static int BO=2;
  Socket socket;
  public Client4(String title){
    super(title);
    msgView.setEditable(false);
    kawi=new Button("剪刀");
    bawi=new Button("石头");
    bo=new Button("布");
    add(msgView,"Center");
    Panel p=new Panel();
    p.add(kawi); p.add(bawi); p.add(bo);
    add(p, "South");
    kawi.addActionListener(this);
    bawi.addActionListener(this);
    bo.addActionListener(this);
    pack();
  }
  private void connect(){
    try{
      msgView.append("尝试与服务器的连接.\n");
      socket=new Socket("127.0.0.1", 7777);
      msgView.append("开始游戏.\n");
      reader=new DataInputStream(socket.getInputStream());
      writer=new DataOutputStream(socket.getOutputStream());
    }catch(Exception e){
      msgView.append("连接失败...");
    }  
  }
  public void actionPerformed(ActionEvent ae){
    int player=-1, server=-1;
    if(ae.getSource()==kawi)
      player=KAWI;
    else if(ae.getSource()==bawi)
      player=BAWI;
    else if(ae.getSource()==bo)
      player=BO;  
    if(player==-1)return;
    try{
      writer.writeUTF("OK");
      writer.flush();
      server=reader.readInt();
    }catch(IOException ie){}
    if(player==server)msgView.append("平局.\n");
    else if(player>server || server-player==2)msgView.append("获胜.\n");
    else msgView.append("失败.\n");
  }
  public static void main(String[] args){
    Client4 client=new Client4("剪刀石头布");
    client.setVisible(true);
    client.connect();
  }
}